import { defineStore } from 'pinia'
import { nextTick } from 'vue' // Import nextTick
import type { ComponentSize } from 'element-plus' // Import ComponentSize type
import tinycolor from 'tinycolor2' // Import tinycolor2
import { ref, computed } from 'vue'
import { useToast } from 'vue-toastification'

// REMOVED: Helper type and global declaration for ViewTransition
// Relying on built-in TypeScript DOM types now

// Define the type for formatting options
export interface FormattingOptions {
    indentation: string;
    collapseContent: boolean;
    lineSeparator: '\n' | '\r\n' | '\r';
}

export const useSettingsStore = defineStore('settings', () => {
    const toast = useToast()

    // --- State ---
    const darkMode = ref(false)
    const themeColor = ref('#409EFF') // Default Element Plus primary color
    const layout = ref<'horizontal' | 'vertical'>('horizontal')
    const componentSize = ref<ComponentSize>('default')
    const panelSizes = ref({
        editor: 40,
        visualizer: 60
    })
    const autoRefresh = ref(false)
    const selectedXmlValidator = ref<'fast-xml-parser' | 'libxml2-wasm' | 'none'>('fast-xml-parser')
    const dagre = ref({
        rankdir: 'TB' as 'TB' | 'LR',
        nodesep: 50,
        ranksep: 50
    })
    const selectedParser = ref<'dom' | 'fast-xml' | 'libxml2-wasm'>('dom')
    const formattingOptions = ref<FormattingOptions>({
        indentation: '  ', // Default: 2 spaces
        collapseContent: true, // Default: collapse empty tags
        lineSeparator: '\n' // Default: LF
    })
    const confirmRecursiveDelete = ref(true)
    const rememberLastFolder = ref(true)

    // --- Getters ---
    const currentTheme = computed(() => darkMode.value ? 'dark' : 'light')

    // --- Actions ---
    const setDarkMode = (value: boolean) => {
        darkMode.value = value
        applyTheme()
    }

    const toggleDarkMode = () => {
        darkMode.value = !darkMode.value
        applyTheme()
    }

    const toggleDarkModeWithAnimation = async (x: number, y: number) => {
        // --- Start: Restore animation logic ---
        const isAppearanceTransition =
            typeof (document as any).startViewTransition === 'function' &&
            !window.matchMedia('(prefers-reduced-motion: reduce)').matches

        if (!isAppearanceTransition) {
            console.warn('View Transitions API not supported or reduced motion enabled, falling back to simple toggle.')
            toggleDarkMode()
            return
        }

        const endRadius = Math.hypot(
            Math.max(x, window.innerWidth - x),
            Math.max(y, window.innerHeight - y)
        )

        document.documentElement.style.setProperty('--clip-x', `${x}px`)
        document.documentElement.style.setProperty('--clip-y', `${y}px`)
        document.documentElement.style.setProperty('--clip-r-end', `${endRadius}px`)

        const transition = (document as any).startViewTransition(async () => {
            darkMode.value = !darkMode.value
            applyTheme()
            await nextTick()
        })

        transition.ready.then(() => {
            const smallCircle = `circle(0px at var(--clip-x) var(--clip-y))`
            const largeCircle = `circle(var(--clip-r-end) at var(--clip-x) var(--clip-y))`

            document.documentElement.animate(
                {
                    clipPath: [smallCircle, largeCircle],
                },
                {
                    duration: 500,
                    easing: 'ease-in-out',
                    pseudoElement: '::view-transition-new(root)',
                }
            )
        })
        // --- End: Restore animation logic ---
    }

    const setThemeColor = (color: string) => {
        themeColor.value = color
        applyTheme()
    }

    const setLayout = (newLayout: 'horizontal' | 'vertical') => {
        layout.value = newLayout
    }

    const setDagreDirection = (direction: 'TB' | 'LR') => {
        dagre.value.rankdir = direction
    }

    const setDagreSpacing = (ranksep: number, nodesep: number) => {
        dagre.value.ranksep = ranksep
        dagre.value.nodesep = nodesep
    }

    const setAutoRefresh = (enabled: boolean) => {
        autoRefresh.value = enabled
    }

    const setSelectedParser = (parser: 'dom' | 'fast-xml' | 'libxml2-wasm') => {
        selectedParser.value = parser
    }

    const setSelectedXmlValidator = (validator: 'fast-xml-parser' | 'libxml2-wasm' | 'none') => {
        selectedXmlValidator.value = validator
    }

    const setFormattingIndentation = (indent: string) => {
        formattingOptions.value.indentation = indent
    }

    const setFormattingCollapseContent = (collapse: boolean) => {
        formattingOptions.value.collapseContent = collapse
    }

    const setFormattingLineSeparator = (separator: '\n' | '\r\n' | '\r') => {
        formattingOptions.value.lineSeparator = separator
    }

    const setComponentSize = (size: ComponentSize) => {
        componentSize.value = size
    }

    const applyTheme = () => {
        document.documentElement.classList.toggle('dark', darkMode.value)
        
        const color = tinycolor(themeColor.value);
        if (!color.isValid()) {
            console.error("Invalid theme color selected:", themeColor.value);
            return; // Don't apply invalid color
        }

        document.documentElement.style.setProperty('--el-color-primary', color.toHexString());

        const lightMix = 80; // For light-8
        const darkMix = 20; // For dark-2

        const light8 = tinycolor.mix('#ffffff', color, 100 - lightMix).toHexString();
        const dark2 = tinycolor.mix('#000000', color, 100 - darkMix).toHexString();
        const light9Color = tinycolor.mix('#ffffff', color, 90); // Keep as tinycolor object
        const light9Hex = light9Color.toHexString();
        const light9Rgb = light9Color.toRgb(); // Get RGB components

        document.documentElement.style.setProperty('--el-color-primary-light-8', light8);
        document.documentElement.style.setProperty('--el-color-primary-dark-2', dark2);
        document.documentElement.style.setProperty('--el-color-primary-light-9', light9Hex); // Set hex for potential direct use
        document.documentElement.style.setProperty('--el-color-primary-light-9-rgb', `${light9Rgb.r}, ${light9Rgb.g}, ${light9Rgb.b}`);

        console.log('Applied theme:', {
            primary: color.toHexString(),
            light8: light8,
            dark2: dark2,
            light9: light9Hex, 
            light9Rgb: `${light9Rgb.r}, ${light9Rgb.g}, ${light9Rgb.b}`,
            darkMode: darkMode.value
        });
    }

    return {
        // State
        darkMode,
        themeColor,
        layout,
        componentSize,
        panelSizes,
        autoRefresh,
        selectedXmlValidator,
        dagre,
        selectedParser,
        formattingOptions,
        confirmRecursiveDelete,
        rememberLastFolder,

        // Getters
        currentTheme,

        // Actions
        setDarkMode,
        toggleDarkMode,
        toggleDarkModeWithAnimation,
        setThemeColor,
        setLayout,
        setDagreDirection,
        setDagreSpacing,
        setAutoRefresh,
        setSelectedParser,
        setSelectedXmlValidator,
        setFormattingIndentation,
        setFormattingCollapseContent,
        setFormattingLineSeparator,
        setComponentSize,
        applyTheme,
    }
}, {
    persist: {
        key: 'jdfsight-settings',
        pick: [
            'darkMode',
            'themeColor',
            'layout',
            'componentSize',
            'panelSizes',
            'autoRefresh',
            'selectedXmlValidator',
            'dagre',
            'selectedParser',
            'formattingOptions',
            'confirmRecursiveDelete',
            'rememberLastFolder'
        ],
        debug: import.meta.env.DEV,
    }
})